package com.huixue.cn.ztej.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huixue.cn.ztej.bean.ApproveBean;
import com.huixue.cn.ztej.bean.EmployApply;
import com.huixue.cn.ztej.bean.Examine;
import com.huixue.cn.ztej.bean.MechanicalApply;
import com.huixue.cn.ztej.bean.Results;
import com.huixue.cn.ztej.bean.User;
import com.huixue.cn.ztej.enums.RoleStatus;
import com.huixue.cn.ztej.service.SysMechanicaApplyService;
import com.huixue.cn.ztej.service.SysProjectService;
import com.huixue.cn.ztej.service.impl.ExamineServiceImpl;
import com.huixue.cn.ztej.utils.Urls;
import com.huixue.cn.ztej.utils.SystemContents.API_RETURN_STATUS;
import com.huixue.cn.ztej.utils.annotation.RequestMappingName;
import com.huixue.cn.ztej.utils.framwork.JacksonUtil;
import com.huixue.cn.ztej.utils.framwork.PageParameter;


@Controller
@RequestMapping(value = "/sys/mechanicalApply")
public class MechanicalApplyController extends BaseController {

	@Autowired
	SysMechanicaApplyService sysMechanicaApplyService;
	
	@Autowired
	private ExamineServiceImpl examineServiceImpl;
	
	@Autowired(required = true)
	SysProjectService sysProjectService;
	
	@RequestMapping(value = "/apply")
	public String apply(Model model) {
		return "/mechan/apply";
	}
	
	@RequestMapping(value = "/save")
	public String saveMechanicaApply(@ModelAttribute("sysProAddForm") MechanicalApply mechanicalApply,
			HttpServletRequest request) {
		mechanicalApply.setApplyTime(new Date());
		sysMechanicaApplyService.saveMechanicaApply(mechanicalApply);
		return "/mechan/list";
	}
	
	
	/*
	 * status = 0 //status 刚申请
	 * status = 1 //工段管理员审批
	 * status = 2 //项目经理审批
	 * status = 3 //部门经理审批
	 * status = 4 //工段管理员审批不通过
	 * status = 5 //项目经理审批不通过
	 * status = 6 //部门经理审批不通过
	 */
	@RequestMappingName(value="跳转到机械审批列表")
	@RequestMapping(value = "/list")
	public String list(@RequestParam(value = "page", defaultValue = "1") Integer page,
			@RequestParam(value = "rows", defaultValue = PageParameter.DEFAULT_PAGE_SIZE+"") Integer rows,
			HttpServletResponse response,HttpServletRequest request,Model model) {
		
		User currentUser = (User)request.getSession().getAttribute("loginUser");
		String status = "-1";
		Map<String, Object> map = new HashMap<String, Object>();
		
		if(currentUser==null){
			return "/mechan/approve/list";
		}
		model.addAttribute("user",currentUser);
		String visaCode = request.getParameter("visaCode");
		if(visaCode!=null && visaCode.trim().length()>0){
			map.put("visaCode", visaCode.trim());
		}
		
		String proejctId = request.getParameter("projectId");
		if(proejctId!=null && proejctId.trim().length()>0 && Integer.valueOf(proejctId) >0 ){
			map.put("proId", proejctId);
			model.addAttribute("projectId", proejctId);
		}
		
		Results projectRes =  sysProjectService.findAll(map);
		model.addAttribute("projectRes", projectRes);
		
		String startDate = request.getParameter("startTime");
		String endDate = request.getParameter("endTime");
		if(startDate!=null){
			map.put("startDate", startDate);
			model.addAttribute("startDate", startDate);
		}
		
		if(endDate!=null){
			map.put("endDate", endDate);
			model.addAttribute("endDate", endDate);
		}
		
		
		//查询机械申请审批
		if(currentUser.getRoleId()!=null){
			if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_3.getRoleId()){
				status = "0,3,-3";
				map.put("proId", currentUser.getProjectID());
				map.put("state", status);
			}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_4.getRoleId()){
				status = "3,4,-4";
				map.put("proId", currentUser.getProjectID());
				map.put("state", status);
				map.put("segmentId", currentUser.getSegmentID());
			}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_5.getRoleId()){
				status = "4,5,-5";
				map.put("proId", currentUser.getProjectID());
				map.put("state", status);
			}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_6.getRoleId()){
				status = "5,6,-6";
				map.put("proId", currentUser.getProjectID());
				map.put("state", status);
			}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_SYSTETM.getRoleId()||
					Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_7.getRoleId()
					||currentUser.getRoleId().equals(RoleStatus.ROLE_8.getRoleId()+"")
					||currentUser.getRoleId().equals(RoleStatus.ROLE_9.getRoleId()+"")){
				String pstate = request.getParameter("pstate");
			    if(pstate!=null && !pstate.equals("")){
			    	map.put("state", pstate);
					model.addAttribute("pstate", pstate);
			    }
			    if(currentUser.getRoleId().equals(RoleStatus.ROLE_8.getRoleId()+"")){
					map.put("proId", currentUser.getProjectID());
				}
			
			}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_2.getRoleId()){
				map.put("applyUserId", currentUser.getUser_id());
			}
			
			//查询机械申请审批
			Results mechanResult = sysMechanicaApplyService.searchMechanicalApplyPage(map,page,rows);
			model.addAttribute("res", mechanResult);
		}		
		
		
		return "/mechan/approve/list";
	}
	
	
	/**
	 * <p>跳转到审批页面</p>
	 */
	@RequestMappingName(value = "跳转到审批页面")
	@RequestMapping(value = "/approve", method = RequestMethod.GET)
	public String toApprove(HttpServletResponse response,HttpServletRequest request,Model model) {
		String applyId = request.getParameter("id");
		MechanicalApply mechapply = sysMechanicaApplyService.findById(Integer.parseInt(applyId));
		model.addAttribute("res", mechapply);
		
		User currentUser = (User)request.getSession().getAttribute("loginUser");
		model.addAttribute("currentUser", currentUser);
		return "/mechan/approve/mechanicalapprove";
	}
	
	@RequestMappingName(value = "跳转到查看页面")
	@RequestMapping(value = "/display", method = RequestMethod.GET)
	public String toDisplay(HttpServletResponse response,HttpServletRequest request,Model model) {
		String applyId = request.getParameter("id");
		MechanicalApply mechapply = sysMechanicaApplyService.findById(Integer.parseInt(applyId));
		List<Examine> list1 = examineServiceImpl.selectByApplyId(Integer.parseInt(applyId),2);
		model.addAttribute("res", mechapply);
		model.addAttribute("list1",list1);
		return "/mechan/approve/mechanicaldisplay";
	}
	
	@RequestMapping(value = "/todo",produces="application/json;charset=UTF-8",method=RequestMethod.POST)
	@ResponseBody
	private Results approve(@RequestBody ApproveBean apply,HttpServletRequest request,HttpServletResponse response,Model model){
		//查找申请
		if(apply.getApplyType()==2){
			MechanicalApply mechanical = sysMechanicaApplyService.findById(apply.getApplyId());
			mechanical.setState(apply.getStatus());
			sysMechanicaApplyService.update(mechanical);
			User currentUser = (User)(request.getSession().getAttribute("loginUser"));;
			
			//添加审批过程
			Examine examine = new Examine();
			examine.setApplyId(apply.getApplyId());
			examine.setExamineId(apply.getApproveUserId());
			examine.setExamineName(apply.getApproveUserName());
			examine.setExamineRoleId(Integer.valueOf(currentUser.getRoleId()));
			//大于0 同意 小于0 不同意
			examine.setState(apply.getStatus()>0?1:2);
			examine.setType(apply.getApplyType());
			//examine.setContent(apply.getStatus()>0?"同意":"不同意");
			if(apply.getStatus()>0){
				if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_3.getRoleId()){
					examine.setContent("物资部审核通过");
				}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_4.getRoleId()){
					examine.setContent("工段管理审核通过");
				}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_5.getRoleId()){
					examine.setContent("合同部审核通过");
				}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_6.getRoleId()){
					examine.setContent("项目部审核通过");
				}
				examine.setState(1);
			}else{
				if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_3.getRoleId()){
					examine.setContent("物资部退回");
				}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_4.getRoleId()){
					examine.setContent("工段退回");
				}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_5.getRoleId()){
					examine.setContent("合同部取消");
				}else if(Integer.valueOf(currentUser.getRoleId())==RoleStatus.ROLE_6.getRoleId()){
					examine.setContent("项目部退回");
				}
				examine.setState(2);
			}
			examine.setExamineTime(new Date());
			examineServiceImpl.add(examine);
			
			
			Results results = new Results("0", "审批成功", "/approve/success");
			
			return results;
		}
		
		return null;
	}
	
	/**
	 * <p>打印申请单</p>
	 */
	@RequestMappingName(value = "打印申请单")
	@RequestMapping(value = "/print", method = RequestMethod.GET)
	public String print(HttpServletResponse response,HttpServletRequest request,Model model) {
		String applyId = request.getParameter("id");
		String url = Urls.BASE_REPORT_URL+"/birt/frameset?__report=mecha_view.rptdesign&applyId="+applyId;
		return "redirect:"+url;
	}
	
	
	@RequestMapping("/updateById/{applyId}")
	@ResponseBody
	public Results updateById(@PathVariable("applyId")Integer applyId,HttpServletResponse response,HttpServletRequest request,Model model){
		MechanicalApply mechanicalApply = sysMechanicaApplyService.findById(applyId);
		if(mechanicalApply.getState()<0){
			mechanicalApply.setState(mechanicalApply.getState()-10000);
		}
		sysMechanicaApplyService.update(mechanicalApply);
		
		Results results = new Results(
				API_RETURN_STATUS.NORMAL.value(),
				API_RETURN_STATUS.NORMAL.desc()
				);
		System.out.println(new JacksonUtil().getJson(results));
		return results;
	}
}
